<script setup>

import {reactive,ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter()

import { userStore} from "@/store/index.js";
const userItemStore = userStore();

const ruleForm = reactive({
  account: '',
  password: '',
  checkPass: '',
  email: '',
  validCode: '',
  mobile: ''
})


/////////////// 校验规则
const refRuleForm = ref(null)

const validatePass = (rule, value, callback) => {
  //验证密码不为空
  if (ruleForm.checkPass !== '') {
    //调用方法验证密码的验证器
    refRuleForm.value.validateField('checkPass');
  }
  //验证通过
  callback();
};

const validatePass2 = (rule, value, callback) => {
  if (value !== ruleForm.password) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    //验证通过
    callback();
  }
};

let validateEmail = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入邮箱地址'));
  } else if (!/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/i.test(value)) {
    callback(new Error('请输入正确的邮箱地址'));
  } else {
    callback();
  }
};

const rules=reactive({
  account: [
    {required: true, message: '请输入账号', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {validator: validatePass}
  ],
  checkPass: [
    {required: true, message: '请再次输入密码', trigger: 'blur'},
    {validator: validatePass2}
  ],
  mobile: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ],
  email: [
    {required: true, message: '请输入邮箱地址', trigger: 'blur'},
    {validator: validateEmail}
  ],
  validCode: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
    //最短4个字符，最长4个字符
    {min: 4, max: 4, message: '长度必须是4个字符', trigger: 'blur'}
  ]
})

// 发送邮件验证码
const sendEmail = () => {
  // email校验通过后，再请求后台发送验证码
  refRuleForm.value.validateField('email', valid => {
    console.log('email校验结果：', valid)
    if (valid) {
        // 发送邮件
        axios.get(`/user/sendEmail?email=${ruleForm.email}`).then(res=>{
          ElMessage.success('验证码已发送！');
        }).catch(error=>{
          ElMessage.error('发送失败！');
        })
    }
  })
}

// 注册提交
const submitForm = () => {
  refRuleForm.value.validate(valid => {
    console.log('表单校验结果：', valid)
    if (valid) {
      axios.post('/user/register', ruleForm).then(res=>{

        ElMessage.success('注册成功！');

        // 本地存储token、user
        const user = res.data;
        localStorage.setItem('user', JSON.stringify(user));
        localStorage.setItem('token', res.headers.authorization);

        // 更新用户登录状态
        userItemStore.updateLoginStatus(true)
        userItemStore.updateUser(res.data)

        router.push('/');
      }).catch(error=>{
        ElMessage.error('注册失败！' + error.response.data);
      })
    } else {
      ElMessage.error('表单校验失败，请填写正确的信息！')
      return false;
    }
  })
}

</script>


<template>
  <div class="login-container">
    <el-card class="register-content">
      <span class="register-title">蜗牛书城：用户注册</span>
      <!-- :rules="rules" 设定校验规则 -->
      <el-form ref="refRuleForm" :model="ruleForm"
               status-icon size="small" :rules="rules" label-width="100px"
               class="demo-ruleForm">
        <el-form-item label="账号名" prop="account">
          <el-input v-model="ruleForm.account"
                    placeholder="请输入用户账号" style="width: 250px;"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="ruleForm.password"
                    placeholder="请输入用户密码"
                    style="width: 250px;"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="ruleForm.checkPass"
                    placeholder="请输入确认密码"
                    style="width: 250px;"></el-input>
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="ruleForm.nickname"
                    placeholder="请输入用户昵称" style="width: 250px;"></el-input>
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="ruleForm.realName"
                    placeholder="请输入真实姓名" style="width: 250px;"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input type="mobile" v-model="ruleForm.mobile"
                    placeholder="请输入正确的手机号"
                    style="width: 250px;"></el-input>
        </el-form-item>
        <!-- 查看ElementPlus的Form组件 -->
        <el-form-item prop="email" label="邮箱地址">
          <el-input v-model="ruleForm.email" placeholder="请输入邮箱地址"
                    style="width: 200px; float: left; margin-right: 5px;"></el-input>
          <el-button type="primary" @click="sendEmail()">发送验证码</el-button>
        </el-form-item>

        <el-form-item prop="validCode" label="验证码">
          <el-input v-model="ruleForm.validCode"
                    placeholder="请输入验证码" style="width: 140px" minlength="4"
                    maxlength="4">
          </el-input>
        </el-form-item>

        <div class="register-submit">
          <el-button type="success" @click="submitForm('ruleForm')" style="width: 150px;"
                     icon="el-icon-user-solid">提交
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>


<style scoped>
.login-container {
  position: fixed;
  height: 100%;
  width: 100%;
  left: 0;
  background-image: linear-gradient(0, rgb(68, 68, 235), lightblue);
  display: flex;
  /* 水平居中对齐 */
  justify-content: center;
  /* 垂直居中对齐 */
  height: 100%;
}

.register-content {
  margin: 10px auto;
  border-radius: 5px;
  padding: 10px;
  width: 480px;
  height: 560px;
}

.register-title {
  font-size: 20px;
}

.register-submit {
  text-align: center;
}

</style>
